package org.zcl.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Component;
import org.zcl.service.LogService;

/**
 * @PROJECT_NAME:
 * @DESCRIPTION:
 * @USER: ZhuChengLin
 * @DATE: 2021/11/25 9:40
 */
@Slf4j
@Aspect
@Component
public class OperatorLogAspect {

    @Autowired
    private LogService logService;

    //解析spel表达式
    ExpressionParser parser = new SpelExpressionParser();
    //将方法参数纳入Spring管理
    LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();

    @Pointcut("@annotation(org.zcl.annotation.LogRecord)")
    public void brokerAspect() {
    }

    @Before("brokerAspect()")
    public void before() {
        System.out.println("@Before");
    }

    @After("brokerAspect()")
    public void after() {
        System.out.println("@After");
    }

    @AfterReturning("brokerAspect()")
    public void afterReturning() {
        System.out.println("@AfterReturning");
    }

    @AfterThrowing("brokerAspect()")
    public void afterThrowing() {
        System.out.println("@AfterThrowing");
    }


    @Around("brokerAspect()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("@Around前环绕通知");
        /*//获取参数对象数组
        Object[] args = pjp.getArgs();
        //获取方法
        Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        LogRecord logRecord = method.getAnnotation(LogRecord.class);
        String spel = logRecord.content();
        //获取方法参数名
        String[] params = discoverer.getParameterNames(method);
        //将参数纳入Spring管理
        EvaluationContext context = new StandardEvaluationContext();
        for (int len = 0; len < Objects.requireNonNull(params).length; len++) {
            context.setVariable(params[len], args[len]);
        }
        Expression expression = parser.parseExpression(spel);
        spel = expression.getValue(context, String.class);
        String operate = logRecord.value().getDescription();

        Log log = Log.builder()
                .operator(logRecord.value().getCode())
                .description(operate + spel)
                .createTime(LocalDateTime.now())
                .build();
        logServ ice.addLog(log);*/
        Object proceed = pjp.proceed();
        System.out.println("@Around后环绕通知");
        return proceed;
    }
}
